package com.minutes.in.seconds.ui.event;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.minutes.in.seconds.MisApp;
import com.minutes.in.seconds.R;
import com.minutes.in.seconds.entity.Person;
import com.minutes.in.seconds.ui.screens.AddContactActivity;
import com.minutes.in.seconds.ui.screens.AddMeetingActivity;
import com.minutes.in.seconds.ui.screens.MainActivity;
import com.reptilemobile.MultipleContactsPicker.ContactPickerActivity;

public class AddMeetingEventHandler implements OnClickListener {

	private AddMeetingActivity addMeetingActivity;

	private FragmentManager fragmentManager;

	private AlertDialog dateDialog;

	private CalendarView cal;

	private SimpleDateFormat sdf;

	private String taskDate;

	private Long taskDateLong;

	private EditText fieldTaskDate;

	public AddMeetingEventHandler(AddMeetingActivity addMeetingActivity) {
		super();
		this.addMeetingActivity = addMeetingActivity;

		fragmentManager = addMeetingActivity.getActivity().getSupportFragmentManager();

		fieldTaskDate = addMeetingActivity.getStartDate();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edtStartDate:
			pickStartDate();

			break;
		case R.id.edtStartTime:
			pickStartTime();

			break;
		case R.id.edtEndTime:
			pickEndTime();

			break;
		case R.id.btnAddMeeting:
			addMeeting();

			break;
		case R.id.layoutAddSpeaker:
			addSpeaker();

			break;
		case R.id.layoutAddAttendee:
			addAttendee();

			break;
		case R.id.layoutAddVoiceNote:
			addVoiceNote();

			break;

		default:
			break;
		}

	}

	@SuppressLint("SimpleDateFormat")
	private void pickStartDate() {
		AlertDialog diaBox = dateDialogBox();
		diaBox.show();
		cal = (CalendarView) diaBox.findViewById(R.id.calendarView);
		sdf = new SimpleDateFormat("dd-MM-yyyy");

		if (fieldTaskDate.length() == 0) {
			// Use current date.
			Calendar date = Calendar.getInstance();
			String curDate = sdf.format(date.getTime());
			dateDialog.setTitle(curDate);
			taskDate = curDate;
			taskDateLong = date.getTimeInMillis();

		} else if (fieldTaskDate.length() > 0) {
			// Use user inputted date.
			String dateFromField = fieldTaskDate.getText().toString();
			DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
			long dateInLong;
			try {
				Date date2 = formatter.parse(dateFromField);
				dateInLong = date2.getTime();
				cal.setDate(dateInLong);
				dateDialog.setTitle(dateFromField);
				taskDate = dateFromField;
				taskDateLong = dateInLong;
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		cal.setOnDateChangeListener(new OnDateChangeListener() {
			@Override
			public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
				String curDate = sdf.format(cal.getDate());
				Log.d("USERLOG", "new Date: " + curDate);
				dateDialog.setTitle(curDate);
				taskDate = curDate;
				taskDateLong = cal.getDate();
			}
		});
	}

	private void pickStartTime() {
		openTimePicker(true);
	}

	private void pickEndTime() {
		openTimePicker(false);
	}

	private void addMeeting() {
		String eventId = addEventToCalendar();

		if (eventId == null) {
			Toast.makeText(addMeetingActivity.getActivity(), "An error occurs!", Toast.LENGTH_SHORT).show();
		}

		addAttendeesToEvent(eventId);
		addReminders(eventId);
		
		Toast.makeText(addMeetingActivity.getActivity(), "Meeting is added!", Toast.LENGTH_SHORT).show();
	}

	private void addSpeaker() {
		showContactPopup(true);
	}

	private void addAttendee() {
		showContactPopup(false);
	}

	private void addVoiceNote() {

	}

	private void openTimePicker(final boolean isStartTime) {
		TimePickerDialog mTimePicker;

		Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int minute = cal.get(Calendar.MINUTE);

		String time = "";
		if (isStartTime) {
			time = addMeetingActivity.getStartTime().getText().toString();
		} else {
			time = addMeetingActivity.getEndTime().getText().toString();
		}

		if (!time.equals("")) {
			hour = Integer.valueOf(time.split(":")[0]);
			minute = Integer.valueOf(time.split(":")[1]);
		}

		mTimePicker = new TimePickerDialog(addMeetingActivity.getActivity(), TimePickerDialog.THEME_HOLO_LIGHT, new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				String time = hourOfDay + ":" + minute;

				if (isStartTime) {
					addMeetingActivity.getStartTime().setText(time);
				} else {
					addMeetingActivity.getEndTime().setText(time);
				}
			}

		}, hour, minute, true);
		mTimePicker.setTitle(addMeetingActivity.getString(R.string.select_start_time));
		mTimePicker.show();
	}

	@SuppressLint("InflateParams")
	private AlertDialog dateDialogBox() {
		LayoutInflater inflater = addMeetingActivity.getActivity().getLayoutInflater();
		View view = inflater.inflate(R.layout.calendar_view, null);

		dateDialog = new AlertDialog.Builder(addMeetingActivity.getActivity()).setTitle("Date").setView(view).setPositiveButton("Set Date", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				java.util.GregorianCalendar gCal = new GregorianCalendar();
				gCal.add(Calendar.DATE, -1);
				long lMillis = gCal.getTime().getTime();

				if (taskDateLong != null && taskDateLong < lMillis) {
					fieldTaskDate.setHint("Date cannot be in the past.");
					fieldTaskDate.setText("");
				} else {
					fieldTaskDate.setHint("");
					fieldTaskDate.setText(taskDate);
				}

			}
		}).setNeutralButton("Remove", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				fieldTaskDate.setText("");
			}
		})

		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Don't do anything.
			}
		}).create();
		return dateDialog;
	}

	private void showContactPopup(final boolean isSpeaker) {
		final Dialog dialogNotification = new Dialog(addMeetingActivity.getActivity());
		dialogNotification.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogNotification.setContentView(R.layout.dialog_add_contact);

		Button btnPhoneContacts = (Button) dialogNotification.findViewById(R.id.btnPhoneContacts);
		btnPhoneContacts.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialogNotification.dismiss();

				Intent contactPicker = new Intent(addMeetingActivity.getActivity(), ContactPickerActivity.class);
				if (isSpeaker) {
					addMeetingActivity.getActivity().startActivityForResult(contactPicker, 1001);
				} else {
					addMeetingActivity.getActivity().startActivityForResult(contactPicker, 1002);
				}
			}
		});

		Button btnNewContacts = (Button) dialogNotification.findViewById(R.id.btnNewContacts);
		btnNewContacts.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialogNotification.dismiss();

				Intent myIntent = new Intent(addMeetingActivity.getActivity(), AddContactActivity.class);
				addMeetingActivity.getActivity().startActivity(myIntent);
			}
		});

		dialogNotification.show();
	}

	private String addEventToCalendar() {
		long startMillis = 0;
		long endMillis = 0;

		String dateStr = addMeetingActivity.getStartDate().getText().toString();

		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

		Date date;
		try {
			date = formatter.parse(dateStr);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);

			String startTimeStr = addMeetingActivity.getStartTime().getText().toString();
			String[] startTimeArr = startTimeStr.split(":");
			String endTimeStr = addMeetingActivity.getEndTime().getText().toString();
			String[] endTimeArr = endTimeStr.split(":");

			Calendar beginTime = Calendar.getInstance();
			beginTime.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), Integer.valueOf(startTimeArr[0]), Integer.valueOf(startTimeArr[1]));
			startMillis = beginTime.getTimeInMillis();
			Calendar endTime = Calendar.getInstance();
			endTime.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), Integer.valueOf(endTimeArr[0]), Integer.valueOf(endTimeArr[1]));
			endMillis = endTime.getTimeInMillis();

			ContentResolver cr = addMeetingActivity.getActivity().getContentResolver();
			ContentValues values = new ContentValues();
			values.put(Events.DTSTART, startMillis);
			values.put(Events.DTEND, endMillis);
			values.put(Events.TITLE, addMeetingActivity.getMeetingTitle().getText().toString());
			values.put(Events.DESCRIPTION, addMeetingActivity.getComment().getText().toString());
			values.put(Events.CALENDAR_ID, MisApp.calendarId);
			values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
			Uri uri = cr.insert(Events.CONTENT_URI, values);

			// get the event ID that is the last element in the Uri
			String eventID = uri.getLastPathSegment();

			return eventID;
		} catch (ParseException e) {
			return null;
		}
	}

	private void addAttendeesToEvent(String eventId) {
		ContentResolver cr = addMeetingActivity.getActivity().getContentResolver();
		ContentValues values = new ContentValues();

		MainActivity mainActivity = (MainActivity) addMeetingActivity.getActivity();
		List<Person> speakers = mainActivity.getSpeakers();
		List<Person> attendees = mainActivity.getAttendees();

		for (Person speaker : speakers) {
			values.put(Attendees.ATTENDEE_NAME, speaker.getName());
			values.put(Attendees.ATTENDEE_EMAIL, speaker.getEmail());
			values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_SPEAKER);
			values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
			values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_INVITED);
			values.put(Attendees.EVENT_ID, eventId);
			cr.insert(Attendees.CONTENT_URI, values);
		}

		for (Person attendee : attendees) {
			values.put(Attendees.ATTENDEE_NAME, attendee.getName());
			values.put(Attendees.ATTENDEE_EMAIL, attendee.getEmail());
			values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
			values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
			values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_INVITED);
			values.put(Attendees.EVENT_ID, eventId);
			cr.insert(Attendees.CONTENT_URI, values);
		}
	}
	
	private void addReminders(String eventId) {
		ContentResolver cr = addMeetingActivity.getActivity().getContentResolver();
		ContentValues values = new ContentValues();
		values.put(Reminders.MINUTES, 10);
		values.put(Reminders.EVENT_ID, eventId);
		values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
		cr.insert(Reminders.CONTENT_URI, values);
		
		values = new ContentValues();
		values.put(Reminders.MINUTES, 1);
		values.put(Reminders.EVENT_ID, eventId);
		values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
		cr.insert(Reminders.CONTENT_URI, values);
	}
}
